package creatnews.utils;

import java.sql.*;

/**
 * @author 愿得一人心
 * @date 2022/2/25 11:22
 */
public class Dbutil {
    public static final String URL = "jdbc:mysql://localhost:3306/news";
    public static final String USER = "root";
    public static final String PASSWORD = "root";
    private static Connection conn = null;

    static {
        try {
            //1.加载驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2. 获得数据库连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        return conn;
    }

    public static void main(String[] args) throws Exception {
        //1.加载驱动程序
        //2. 获得数据库连接
        Connection conn = Dbutil.getConnection();
        //3.操作数据库，实现增删改查
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * from news_topic");
        //如果有数据，rs.next()返回true
        while (rs.next()) {
            System.out.println(rs.getInt("id") + " 主题：" + rs.getString("topicname") + "注册时间"+ rs.getDate("createtime"));
        }
    }
}